package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController("adminDishController")
@RequestMapping("/admin/dish")  // 将路径放在这里
@Slf4j
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    RedisTemplate redisTemplate;


    public void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
    @ApiOperation("保存口味")
    @PostMapping
    public Result<Object> saveWithFlavors(@RequestBody DishDTO dishDTO){

        String key = "dish_" + dishDTO.getCategoryId();
        dishService.saveWithFlavors(dishDTO);
        //redis中装的是一个cId对应一个分类的菜品列表
        //因为保存口味后，缓存中的数据需要更新；可以指定删除的缓存cId,不用删除所有缓存
        cleanCache(key);
        return Result.success();
    }
    /**
     * 菜品分页查询*
     * @param dishPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO) {
        log.info("菜品分页查询:{}", dishPageQueryDTO);
        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);//后绪步骤定义

        return Result.success(pageResult);
    }

    @DeleteMapping("")
    @ApiOperation("批量删除菜品")
    public Result deleteDishes(@RequestParam("ids" +
            "") List<Long> idList){
        dishService.deleteBataches(idList);
        cleanCache("dish_*");
        return Result.success();
    }
    @PostMapping("/status/{status}")
    public Result updateDishStatus(@PathVariable int status,@RequestParam int id){
        dishService.updateDishStatus(id,status);

        //直接全部清，不然还要查
        cleanCache("dish_*");
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> list(@RequestParam  long categoryId){
        return Result.success(dishService.getByCId(categoryId));
    }

}

